package com.ljfiction.book.activitys;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.BookIfoBean;
import com.ljfiction.book.Baner.CreatBaocunBean;
import com.ljfiction.book.Dialog.ImageDialog;
import com.ljfiction.book.Dialog.TocunDialog;
import com.ljfiction.book.Dialog.WxkefuDialog;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.CreatChapterSettingManager;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.ShareTool;
import com.ljfiction.book.tools.StringTool;
import com.ljfiction.book.tools.TimeTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;

import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class MyBookActivity extends BaseActivity {

    @BindView(R.id.daohanglan_mybook)
    LinearLayout daohanglanMybook;
    @BindView(R.id.back_mybook)
    ImageView backMybook;

    @BindView(R.id.isqianyue_mybook)
    SuperButton isqianyueMybook;
    @BindView(R.id.bookname_mybooks)
    TextView booknameMybooks;
    @BindView(R.id.addsection)
    LinearLayout addsection;
    @BindView(R.id.toseesection)
    LinearLayout toseesection;
    @BindView(R.id.lookatthedraft)
    LinearLayout lookatthedraft;
    @BindView(R.id.issigen)
    TextView issigen;
    @BindView(R.id.isissigen)
    TextView isissigen;
    @BindView(R.id.contractstatus)
    LinearLayout contractstatus;


    @BindView(R.id.iswanjie_mybook)
    TextView iswanjieMybook;
    @BindView(R.id.isshenhetext)
    TextView isshenhetext;
    @BindView(R.id.shenqingshenhe)
    TextView shenqingshenhe;
    @BindView(R.id.isshenhe)
    LinearLayout isshenhe;
    @BindView(R.id.isshangjia)
    TextView isshangjia;
    @BindView(R.id.mybookimage_mybook)
    ImageView mybookimageMybook;

    @BindView(R.id.jianjie_mybook)
    TextView jianjieMybook;

    private ImageDialog imageDialog;

    private String bookId;
    private BookIfoBean.DataBean.BookDataInfoBean bookInfor;
    private Intent intent;
    private JSONObject js;
    private WxkefuDialog wxkefuDialog;
    private TocunDialog tocunDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_book);
        ButterKnife.bind(this);
        bookId = getIntent().getStringExtra("bookId");
        intData();
    }

    private void intData() {
        if (CreatChapterSettingManager.getInstance().getIsShangchuan(bookId) == 0) {
            tocungao();
        }
        OkHttpUtils.post(HttpManager.IP + "/book-showBookInfoApp")

                .params("bookid", bookId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                Gson g = new Gson();
                                /*isissigen.setText("编辑QQ："+ js.getJSONObject("data").getString("qq1"));
                                shenqingshenhe.setText("客服QQ："+ js.getJSONObject("data").getString("qq2"));*/
                                bookInfor = g.fromJson(s, BookIfoBean.class).getData().getBookDataInfo();
                                intView();
                            } else {
                                goBack();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void tocungao() {
        String chapter = "";
        CreatBaocunBean creatbaocun = CreatChapterSettingManager.getInstance().getCreatObject(bookId);
        if (creatbaocun == null) {
            return;
        }
        chapter = StringTool.getChapterText(creatbaocun.getChapterContent());
        if (creatbaocun.getIsfromCaogao() == 1) {
            OkHttpUtils.post(HttpManager.IP + "/chapter-update")

                    .params("chapterTitle", creatbaocun.getChapterTitle())
                    .params("bookId", bookId)
                    .params("bookWriterId", UserManageBean.userBean.getUserId())
                    .params("chapterContent", chapter)
                    .params("releaseTime", creatbaocun.getTime())
                    .params("chapterLength", StringTool.getChapterTextLength(chapter))
                    .params("volumeId", creatbaocun.getVolumeId())
                    .params("whetherPublic", "1")
                    .params("id", String.valueOf(creatbaocun.getChapterId()))
                    .params("authorWords", creatbaocun.getAuthorSay())
                    .execute(new StringCallback() {
                        @Override
                        public void onBefore(BaseRequest request) {
                            super.onBefore(request);
                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {

                            try {
                                JSONObject js = new JSONObject(s);
                                if (js.getInt("returnCode") == 200) {
                                    showToast("同步成功");
                                    CreatChapterSettingManager.getInstance().saceIsShangchuan(bookId, 1);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } else {
            OkHttpUtils.post(HttpManager.IP + "/chapter-creates")

                    .params("bookId", bookId)
                    .params("bookWriterId", String.valueOf(UserManageBean.userBean.getUserId()))
                    .params("bookTitle", creatbaocun.getBookName())
                    .params("chapterTitle", creatbaocun.getChapterTitle())
                    .params("chapterContent", chapter)
                    .params("releaseTime", TimeTool.getThistime())
                    .params("chapterIsvip", String.valueOf(0))
                    .params("volumeId", creatbaocun.getVolumeId())
                    .params("whetherPublic", "1")
                    .params("chapterLength", StringTool.getChapterTextLength(chapter))
                    .params("authorWords", creatbaocun.getAuthorSay())
                    .execute(new StringCallback() {
                        @Override
                        public void onBefore(BaseRequest request) {
                            super.onBefore(request);

                        }

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            try {
                                JSONObject js = new JSONObject(s);
                                if (js.getInt("returnCode") == 200) {
                                    showToast("同步成功");
                                    CreatChapterSettingManager.getInstance().saceIsShangchuan(bookId, 1);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        }
    }

    private void intView() {
        Glide.with(this).load(bookInfor.getBookImage()).into(mybookimageMybook);
        booknameMybooks.setText(bookInfor.getBookName());
        jianjieMybook.setText(bookInfor.getBookIntroduction());
        if (bookInfor.getBookCheckStatus() == 0) {
            isqianyueMybook.setText("未审核");
            isqianyueMybook.setsSolidColor("#666666");
        } else if (bookInfor.getBookCheckStatus() == 1) {
            if (bookInfor.getBookAuthorization() == 0 || bookInfor.getBookAuthorization() == 3) {
                isqianyueMybook.setsSolidColor("#666666");
                isqianyueMybook.setText("未签约");
            } else {
                isqianyueMybook.setsSolidColor("#75D5F8");
                isqianyueMybook.setText("已签约");
            }

        } else {
            isqianyueMybook.setText("VIP");
        }
        if (bookInfor.getBookAuthorization() == 0 || bookInfor.getBookAuthorization() == 3) {
            issigen.setTextColor(Color.parseColor("#333333"));
            issigen.setText("未签约");
        } else {
            issigen.setTextColor(Color.parseColor("#999999"));
            contractstatus.setClickable(false);
            issigen.setText("已签约");
            isissigen.setVisibility(View.GONE);

        }
        switch (bookInfor.getBookCheckStatus()) {
            case 0:

                break;
            case 1:
                isshenhetext.setTextColor(Color.parseColor("#999999"));
                isshenhetext.setText("已审核");
                isshenhe.setClickable(false);
                shenqingshenhe.setVisibility(View.GONE);
                break;
            case 2:
                isshenhetext.setTextColor(Color.parseColor("#999999"));
                isshenhetext.setText("已审核");
                isshenhe.setClickable(false);
                shenqingshenhe.setVisibility(View.GONE);
                isshangjia.setTextColor(Color.parseColor("#999999"));
                isshangjia.setText("已上架");
                break;
            default:

                break;
        }

        if (bookInfor.getBookStatus() == 0) {
            iswanjieMybook.setText("连载中...");
        } else {
            iswanjieMybook.setText("完结");
            iswanjieMybook.setTextColor(Color.parseColor("#FB5E6F"));
        }

    }

    @OnClick({R.id.back_mybook, R.id.mybookimage_mybook, R.id.addsection, R.id.toseesection, R.id.lookatthedraft, R.id.contractstatus, R.id.bianjijj, R.id.isshenhe, R.id.share_writer})
    public void onViewClicked(View view) {
        if (bookInfor == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.back_mybook:
                goBack();
                break;
            case R.id.share_writer:

                ShareTool.toShare(MyBookActivity.this, bookInfor.getBookName(), bookId, bookInfor.getBookImage(), bookInfor.getBookIntroduction(), String.valueOf(UserManageBean.userBean.getUserId()));
                break;
            case R.id.mybookimage_mybook:
                imageDialog = new ImageDialog(this, "logoName.jpg", new ImageDialog.Listener() {
                    @Override
                    public void getImage(final Bitmap photo) {
                        OkHttpUtils.post(HttpManager.IP + "/sys-BookCoverAvatarimgUpload")

                                .params("bookid", bookId)
                                .params("file", new File(getExternalCacheDir() + "/logoName.jpg"))
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(s);
                                            if (jsonObject.getInt("returnCode") == 200) {
                                                mybookimageMybook.setImageBitmap(photo);
                                                showToast(jsonObject.getString("msg"));
                                            } else {
                                                showToast(jsonObject.getString("msg"));
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    }
                });
                break;
            case R.id.addsection:
                intent = new Intent(this, ArticleActivity.class);
                intent.putExtra("bookId", bookId);
                intent.putExtra("bookName", bookInfor.getBookName());
                intent.putExtra("isCaogao", 0);
                intent.putExtra("isvip", bookInfor.getBookCheckStatus());
                startActivity(intent);
                break;
            case R.id.toseesection:
                intent = new Intent(MyBookActivity.this, MyBookvolemuActivity.class);
                intent.putExtra("bookId", bookId);
                startActivity(intent);
                break;
            case R.id.lookatthedraft:
                intent = new Intent(this, SketchActivity.class);
                intent.putExtra("bookId", bookId);
                if (bookInfor.getBookCheckStatus() > 1) {
                    intent.putExtra("isVip", 1);
                } else {
                    intent.putExtra("isVip", 0);
                }

                startActivity(intent);
                break;
            case R.id.contractstatus:
                if (wxkefuDialog == null) {
                    wxkefuDialog = new WxkefuDialog(MyBookActivity.this);
                }
                wxkefuDialog.show();
                /*String appId = "wx3c440c21cdf7452b";//开发者平台ID
                IWXAPI api = WXAPIFactory.createWXAPI(MyBookActivity.this, appId, false);

                if (api.isWXAppInstalled()) {
                    JumpToBizProfile.Req req = new JumpToBizProfile.Req();
                    req.toUserName = "gh_47a5bb6558e0"; // 公众号原始ID
                    req.extMsg = "";
                    req.profileType = JumpToBizProfile.JUMP_TO_NORMAL_BIZ_PROFILE; // 普通公众号
                    api.sendReq(req);
                }else{
                    showToast( "请检查是否安装微信");
                }
*/
               /* try {
                    if (js!=null&&js.getJSONObject("data")!=null&&js.getJSONObject("data").getString("qq1")!=null){
                        url = "mqqwpa://im/chat?chat_type=wpa&uin="+js.getJSONObject("data").getString("qq1");
                    }else {
                        //第二种方式：可以跳转到添加好友，如果qq号是好友了，直接聊天
                        //uin是发送过去的qq号码
                        url = "mqqwpa://im/chat?chat_type=wpa&uin=3310635242";
                    }

                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast( "请检查是否安装QQ");
                }*/
                break;
            case R.id.bianjijj:
                intent = new Intent(MyBookActivity.this, EditJianjieActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("bookId", bookId);
                intent.putExtra("jianjietext", bookInfor.getBookIntroduction());
                startActivityForResult(intent, 5);
                break;
            case R.id.isshenhe:
                if (wxkefuDialog == null) {
                    wxkefuDialog = new WxkefuDialog(MyBookActivity.this);
                }
                wxkefuDialog.show();
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (bookInfor.getBookCheckStatus() > 0&&SettingManager.getInstance().getNewChapterNum()%4==0) {
            if (tocunDialog == null) {
                tocunDialog = new TocunDialog(this);
                tocunDialog.setListener(new TocunDialog.Listener() {
                    @Override
                    public void back() {
                        ShareTool.toSharexiaochengxu(bookId, bookInfor.getBookName(), bookInfor.getBookImage());
                    }

                    @Override
                    public void cuntocungao() {
                        Intent intent = new Intent(MyBookActivity.this, ReaderAidActivity.class);
                        startActivity(intent);

                    }
                }, "酒香也怕巷子深\n快让更多的人看到你的故事！", "召唤伙伴", "我的应援");
            }
            SettingManager.getInstance().saveNewChapterNum();
            tocunDialog.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 5 && resultCode == 5) {
            bookInfor.setBookIntroduction(data.getStringExtra("jianjietext"));
            jianjieMybook.setText(bookInfor.getBookIntroduction());
        } else if (requestCode == 5) {

        } else if (resultCode == Activity.RESULT_OK) {
            imageDialog.onActivityResult(data, requestCode, 0);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
